package han.cirno.corrupt.components.crash

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import han.cirno.corrupt.util.ViewUtil.getString
import java.io.File

object CrashUtils {
    fun Context.sendCrashReport(crashFilePath:String){
        val tempFile= File(crashFilePath).also { if(!it.exists())return }
        val sendIntent = Intent()
        val uri = if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
            FileProvider.getUriForFile(this, "$packageName.FILE_PROVIDER",tempFile)
        }else{
            Uri.fromFile(tempFile)
        }
        sendIntent.setAction(Intent.ACTION_SEND)
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri)
        sendIntent.setType("text/plain")
        startActivity(Intent.createChooser(sendIntent,""))
    }

    private fun genCrashReport(t: Thread, e: Throwable): String {
        val s =
            """
-------- Corrupt crash report --------
Thread name:${t.name}
Thread stack trace:
${t.stackTrace.joinToString("\n") { it.toString() }}
Exception stack trace:
${e.stackTraceToString()}""".trimIndent()
        return s
    }

    private fun genTaskFailedReport(name:Int?, throwable: Throwable):String{
        val translatedName=try{
            getString(name!!)
        }catch (e:Exception){
            "[Error in translate name]\nDetail: ${e.stackTraceToString()}"
        }
        return ""+
"""
-------- Corrupt task failed report --------
Task name: $name
Translated name: $translatedName
Exception stack trace:
${throwable.stackTraceToString()}
""".trimIndent()
    }

    fun makeCrashReportFile(t: Thread,e: Throwable):Pair<String,File>{
        val report = genCrashReport(t, e)
        val tempFile= File.createTempFile("${CrashTypes.CRASH}-${System.currentTimeMillis()}",".txt")
        tempFile.writeBytes(report.toByteArray(Charsets.UTF_8))
        return report to tempFile
    }

    fun makeTaskFailedReport(name: Int?,throwable: Throwable):Pair<String,File>{
        val report = genTaskFailedReport(name, throwable)
        val tempFile= File.createTempFile("taskFailed-${System.currentTimeMillis()}",".txt")
        tempFile.writeBytes(report.toByteArray(Charsets.UTF_8))
        return report to tempFile
    }
}